<?php
/**
 * @title 48. 旋转图像
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $matrix
     * @return NULL
     */
    function rotate(&$matrix) {
        /**
         * @since 2020-07-21 长度
         */
        $n = count($matrix);

        /**
         * @since 2020-07-21 特殊情况排除
         */
        if($n == 1){
            return $matrix;
        } else {}

        /**
         * @since 2020-07-21 旋转
         */
        $w = $n;
        $k = 0;
        for($i=0, $iMax = ($n-2)>>1; $i<=$iMax; $i++){
            for($j=$k, $jMax = $w-2+$k; $j<=$jMax; $j++){
                // $Ai = $i;
                // $Aj = $j;
                // $Bi = $j;
                // $Bj = $k+$w-1;
                // $Ci = $k+$w-1;
                // $Cj = $n-1-$j;
                // $Di = $n-1-$j;
                // $Dj = $k;
                // echo "[{$Ai}, {$Aj}] => [{$Bi}, {$Bj}] => [{$Ci}, {$Cj}] => [{$Di}, {$Dj}]", PHP_EOL;

                list($matrix[$i][$j], $matrix[$j][$k+$w-1], $matrix[$k+$w-1][$n-1-$j], $matrix[$n-1-$j][$k]) = [$matrix[$n-1-$j][$k], $matrix[$i][$j], $matrix[$j][$k+$w-1], $matrix[$k+$w-1][$n-1-$j]];
                /**
                 * @since 2020-07-21 四个交换点
                 *
                 * |←            n           →|
                 * |← k →| |←   w    →| |← k →|
                 *
                 *                      -
                 * |←    j    →|        ↑
                 *         → → a → → →  j
                 *         ↑         ↓  ↓
                 *         ↑         b  -
                 *      -  d         ↓
                 *      ↑  ↑         ↓
                 *      j  ← ← ← c ← ↓
                 *      ↓       |←    j    →|
                 *      -
                 */
            }

            $k++;
            $w -= 2;
        }

        /**
         * @return
         */
        return $matrix;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.21_6.php
 */
$datas = [
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ],
    [
        [ 5, 1, 9,11],
        [ 2, 4, 8,10],
        [13, 3, 6, 7],
        [15,14,12,16]
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->rotate($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
